package com.wjh.anyview.quartz.listener;

import com.wjh.anyview.quartz.job.BeginExamJob;
import com.wjh.anyview.quartz.job.EndExamJob;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * 启动监听器，启动springboot项目后就执行
 *
 * @author wjh
 * @date 2021/10/22 1:37
 * @Package com.wjh.anyview.quartz.listener
 */
@Component
public class StartApplicationListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private Scheduler scheduler;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //定义执行给定作业的计划的组件triggerKey
        TriggerKey triggerKey = TriggerKey.triggerKey("triggerKey1", "group1");
        try {
            Trigger trigger = scheduler.getTrigger(triggerKey);
            if (trigger == null) {
                trigger = TriggerBuilder.newTrigger()
                        .withIdentity(triggerKey)
                        //每隔10秒查询一次是否要正式开始当前考试
                        .withSchedule(CronScheduleBuilder.cronSchedule("0/10 * * * * ?"))
                        .build();

                //定义作业的实例jobDetail，执行的作业是BeginExamJob
                JobDetail jobDetail = JobBuilder.newJob(BeginExamJob.class)
                        .withIdentity("job1", "group1")
                        .build();
                //添加进任务调度器
                scheduler.scheduleJob(jobDetail, trigger);
            }

            //定义执行给定作业的计划的组件triggerKey2
            TriggerKey triggerKey2 = TriggerKey.triggerKey("triggerKey2", "group2");
            Trigger trigger2 = scheduler.getTrigger(triggerKey2);
            if (trigger2 == null) {
                trigger2 = TriggerBuilder.newTrigger()
                        .withIdentity(triggerKey2)
                        //每隔一分钟查询一次是否要结束考试
                        .withSchedule(CronScheduleBuilder.cronSchedule("0 */1 * * * ?"))
                        .build();

                //定义作业的实例jobDetail，执行的作业是EndExamJob
                JobDetail jobDetail2 = JobBuilder.newJob(EndExamJob.class)
                        .withIdentity("job2", "group2")
                        .build();
                //添加进任务调度器
                scheduler.scheduleJob(jobDetail2, trigger2);
            }

            //启动任务调度器
            scheduler.start();
        } catch (SchedulerException e) {
            e.printStackTrace();
        }

    }

}
